package com.cloud.quickconfigure.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 手动---动态生成队列--交换机--绑定
 *
 * @author NiJo_H
 * @version 1.0
 * @date 2019/9/22 22:10
 */
@Service
public class MqService {

    @Autowired
    private RabbitAdmin rabbitAdmin;

    /**
     * 动态生成topic模式队列
     *
     * @param queueName    队列名
     * @param exchangeName 交换机名称
     * @param rouleKey     路由键
     * @return
     */
    public void topicBinding(String queueName, String exchangeName, String rouleKey) {
        if (Objects.isNull(rabbitAdmin.getQueueProperties(queueName))) {
            Queue queue = new Queue(queueName, true, false, false, null);
            rabbitAdmin.declareQueue(queue);
            TopicExchange topicExchange = new TopicExchange(exchangeName);
            //声明exchange
            rabbitAdmin.declareExchange(topicExchange);
            //将queue绑定到exchange
            Binding binding = BindingBuilder.bind(queue).to(topicExchange).with(rouleKey);
            //声明绑定关系
            rabbitAdmin.declareBinding(binding);
        }
    }

    /**
     * 动态生成fanout模式队列
     *
     * @param queueName    队列名
     * @param exchangeName 交换机名称
     * @return
     */
    public void fanoutBinding(String queueName, String exchangeName) {
        if (Objects.isNull(rabbitAdmin.getQueueProperties(queueName))) {
            Queue queue = new Queue(queueName, true, false, false, null);
            rabbitAdmin.declareQueue(queue);
            FanoutExchange fanoutExchange = new FanoutExchange(exchangeName);
            //声明exchange
            rabbitAdmin.declareExchange(fanoutExchange);
            //将queue绑定到exchange
            Binding binding = BindingBuilder.bind(queue).to(fanoutExchange);
            //声明绑定关系
            rabbitAdmin.declareBinding(binding);
        }
    }

    /**
     * 动态生成direct模式队列
     *
     * @param queueName    队列名
     * @param exchangeName 交换机名称
     * @param rouleKey     路由键
     * @return
     */
    public void redirectBinding(String queueName, String exchangeName, String rouleKey) {
        if (Objects.isNull(rabbitAdmin.getQueueProperties(queueName))) {
            Queue queue = new Queue(queueName, true, false, false, null);
            rabbitAdmin.declareQueue(queue);
            DirectExchange directExchange = new DirectExchange(exchangeName);
            //声明exchange
            rabbitAdmin.declareExchange(directExchange);
            //将queue绑定到exchange
            Binding binding = BindingBuilder.bind(queue).to(directExchange).with(rouleKey);
            //声明绑定关系
            rabbitAdmin.declareBinding(binding);
        }

    }


}
